// 获取经纬度
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: "wgs84",
      success: function (res) {
        const latitude = res.latitude; // 纬度
        const longitude = res.longitude; // 经度
        const city = getCityByLocation(latitude, longitude);
        resolve(city);
      },
      fail: function (err) {
        reject(err);
        console.error("获取位置失败：", err);
        uni.showToast({
          title: "获取位置失败，请检查权限或网络",
          icon: "none",
        });
      },
    });
  });
};
// 根据经纬度获取城市信息
export const getCityByLocation = (latitude, longitude) => {
  const ak = "ZuY6HYyh6ZacSqzX2a9HTsma1LGmuAlw"; // 替换为你在百度地图申请的 AK
  const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${ak}&output=json&coordtype=wgs84ll&location=${latitude},${longitude}`;
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      success: function (res) {
        if (res.data.status === 0) {
          const city = res.data.result.addressComponent.city;
          resolve(city);
        } else {
          console.error("逆地理编码失败：", res.data.message);
          uni.showToast({
            title: "获取城市信息失败，请稍后重试",
            icon: "none",
          });
        }
      },
      fail: function (err) {
        reject(err);
        console.error("请求逆地理编码 API 失败：", err);
        uni.showToast({
          title: "网络请求失败，请检查网络连接",
          icon: "none",
        });
      },
    });
  });
};
